package com.jokerpan.project.Handler;

import com.google.gson.Gson;
import com.jokerpan.project.Message.Msg;
import com.jokerpan.project.entity.Users;
import com.jokerpan.project.service.RouteService;
import com.jokerpan.project.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class AuthenticationSuccess implements AuthenticationSuccessHandler {
    @Autowired
    Gson gson;
    @Resource
    public RedisTemplate redisTemplate;
    @Resource
    public UsersService usersService;
    @Resource
    RouteService routeService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        ValueOperations<String, Users> operations = redisTemplate.opsForValue();
        String sessionId = request.getSession().getId();
        String loginName= authentication.getName();
        Users users = usersService.checkLoginName(loginName);
        List<LinkedHashMap<String, Object>> menuData = this.routeService.queryAll(users.getRoleId());
        users.setMenuData(menuData);
        String key = "user_" + sessionId;
        if (redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
        //TODO 登录成功后将用户数据放入redis中
        operations.set(key, users, 3, TimeUnit.HOURS);
        Msg result=Msg.success("登录成功！！！！！",sessionId);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(gson.toJson(result));
    }
}
